<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
        <h2 v-html='salary'></h2>
        <input type="text" v-model='salary'>
        <h3 v-html='salary'></h3>
    </div>
    <script>
        // 设置一个事件中心
        function eventCenter(){
            this.guanjia = {
            }
        }
        // 设置一个监察者 负责添加事件以及处理对应的事件的逻辑
        eventCenter.prototype.$on = function (eventName, fn) {
            if(this.guanjia[eventName]){
                this.guanjia[eventName].push(fn)
            }else {
                this.guanjia[eventName] = [fn]
            }
        }
        // 设置一个执行者
        eventCenter.prototype.$emit = function(eventName) {
            if(this.guanjia[eventName]){
                this.guanjia[eventName].forEach(fn => fn())
            }
        }
    </script>
    <script>
        let ec = new eventCenter()
        function MVVM (options) {
            let { el, data } = options
            for(let key in data){
                Object.defineProperty(this,key,{
                    get () {
                        return data[key]
                    },
                    set (val) {
                        // val 是修改的值
                        // key才是监听的数据salary的名字
                        data[key] = val
                        ec.$emit(key)
                    }
                })
            }
            const elNodes = document.querySelector(el)
            // console.dir(elNodes);
            Array.from(elNodes.children).forEach(node => {
                if(node.hasAttribute('v-html')){
                    let val = node.getAttribute('v-html')
                    node.innerHTML = data[val]
                    ec.$on(val,()=>{
                        node.innerHTML = data[val]
                    })
                }
                if(node.hasAttribute('v-model')){
                    let val = node.getAttribute('v-model')
                    node.value = data[val]
                    ec.$on(val,() => {
                        node.value = data[val]
                    })
                    node.addEventListener('input',e => {
                        let newVal = e.target.value
                        this[val] = newVal
                })
                }
                
            })
            
        }
    </script>
    <script>
        data = {
            salary: 20000
        }
        const vm = new MVVM({
            el:'#app',
            data
        })
    </script>
</body>
</html>